package com.users.rn.common.plugin

import android.content.Context
import com.users.rn.rncommon.plugin.PluginInformation
import org.json.JSONArray
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.lang.Exception

/**

 * 作者：wolf on 1/12/21 11:22

 * 邮箱：bluce

 */

class ParseLocalPlugin(val context: Context) : Runnable {

    companion object {
        const val RN_COMMON_PLUGIN_INFO = ".users_rncommonpluginconfig"
    }
    override fun run() {
        loadAndParseData()
    }

    private fun loadAndParseData() {
        val loadData = loadLocalFile()
        if (loadData == "") {
            return
        }
        try {
            val jsonArray = JSONArray(loadData)
            var index = 0
            while (index < jsonArray.length()) {
                PluginHelper.savePluginInfo(context, PluginInformation.deserialize(jsonArray.getString(index)))
                index++
            }
        } catch (err: Exception) {
            err.printStackTrace()
        }
    }


    /**
     * 读取本地文件
     */
    private fun loadLocalFile(): String {
        var bufferReader: BufferedReader? = null
        try {
            bufferReader = BufferedReader(InputStreamReader(context.resources.assets.open(RNPluginFieldKey.JSON_FILE)))
            return bufferReader.use(BufferedReader::readText)
        } catch (err: Exception) {
            err.printStackTrace()
        } finally {
            try {
                bufferReader?.close()
            } catch (err: IOException) {
                err.printStackTrace()
            }
        }
        return "[]"
    }
}